config_file="/etc/containerd/config.toml"
config_path='/etc/containerd/certs.d'

[ ! -d "${config_file%/*}" ] && mkdir -p ${config_file%/*}
lineno="$(containerd config default | grep -n -A 1 -P '(?<=\[plugins.")io.containerd.grpc.v1.cri(?=".registry])'|tail -1)"
lineno=${lineno/-*}
containerd config default | sed -e "${lineno}s@config.*@config_path = \"${config_path}\"@" |sed '/SystemdCgroup/s/false/true/' | sed "s#registry.k8s.io/pause#registry.aliyuncs.com/google_containers/pause#g" > $config_file

[ ! -d "${config_path}" ] && mkdir -p ${config_path}
params="${@:-registry.k8s.io:k8s.nju.edu.cn docker.io:docker.nju.edu.cn gcr.io:gcr.nju.edu.cn k8s.gcr.io:gcr.nju.edu.cn/google-containers ghcr.io:ghcr.nju.edu.cn quay.io:quay.nju.edu.cn nvcr.io:ngc.nju.edu.cn}"

function content(){
    printf 'server = "https://%s"\n'  "${registry}"
    printf '[host."https://%s"]\n' "${proxy_server}"
    printf '  capabilities = ["pull", "resolve"]'
}

for param in ${params}
do
    registry="${param/:*/}"
    proxy_server="${param/*:/}"
    hosts_path="$config_path/$registry"
    [ ! -d "$hosts_path" ] && mkdir -p ${hosts_path}
    content > $hosts_path/hosts.toml
done

